package com.txq.bilibili.app.utils;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.util.LruCache;


import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * Created by qdJack on 2015/3/11.
 */
public class ImageCache {
    private static ImageCache ourInstance = null;

    public static ImageCache getInstance() {
        if (ourInstance == null) {
            ourInstance = new ImageCache();
        }
        return ourInstance;
    }

    //声明一级缓存
    private LruCache<String,Bitmap> firstCache;
    //声明二级缓存
    private HashMap<String,SoftReference<Bitmap>> secondCache;

    private ImageCache() {

        long freeMemory = Runtime.getRuntime().freeMemory();
        if(freeMemory > 0){
            freeMemory = freeMemory/8;
        }else {
            freeMemory = 5 * 1024 * 1024;
        }
        firstCache = new LruCache<String, Bitmap>((int)freeMemory){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                int size = 0;
                if(Build.VERSION.SDK_INT>=19){
                    size = value.getAllocationByteCount();
                }else {
                    int rowBytes = value.getRowBytes();
                    int height = value.getHeight();
                    size = rowBytes * height;
                }
                return size;
            }
        };
        secondCache = new HashMap<String, SoftReference<Bitmap>>();
    }

    //获取内存中指定的id的图片
    public Bitmap getImage(String url){
        Bitmap ret = null;

        if(url != null){
            ret = firstCache.get(url);
            if(ret == null){
                SoftReference<Bitmap> reference = secondCache.get(url);
                if(reference != null){
                    ret = reference.get();
                }
            }
        }

        return ret;
    }

    public void putImage(String url,Bitmap bitmap){
        if(url != null && bitmap != null){
            //更新一级缓存
            firstCache.put(url,bitmap);
            //更新二级缓存
            secondCache.put(url,new SoftReference<Bitmap>(bitmap));
        }
    }
}
